<template>
  <base-modal
    :show.sync="visible"
    width="420px"
    class="edit-dialog"
    @closed="onClose('form')"
  >
    <div slot="title">
      <span class="el-dialog__title">{{
        id ? $t('event.setting.additional.component.editCardnameDialog.title1') : $t('event.setting.additional.component.editCardnameDialog.title2')
      }}</span>
    </div>
    <div class="base-modal-content">
      <el-form :model="form" :rules="rules" ref="form" label-position="top">
        <el-form-item :label="`${$t('common.base.name')}：`" prop="name">
          <el-input
            v-model="form.name"
            :placeholder="$t('event.setting.additional.component.editCardnameDialog.pla1')"
            maxlength="20"
          ></el-input>
          <base-select-language 
            :field="{}"
            :defaultValueLanguage = "nameLanguage"
            :defaultValue="form.name"
            @save = "saveName"
            v-if="visible"
          ></base-select-language>
        </el-form-item>
        <el-form-item :label="`${$t('common.form.type.description')}：`" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            :placeholder="$t('event.setting.additional.component.editCardnameDialog.pla2')"
            maxlength="500"
          ></el-input>
          <base-select-language 
            :field="{}"
            :defaultValueLanguage = "descriptionLanguage"
            :defaultValue="form.description"
            @save = "saveDescription"
            v-if="visible"
          ></base-select-language>
        </el-form-item>
        <el-form-item prop="resource">
          <div slot="label">
            {{$t('common.base.type')}}
            <el-tooltip
              effect="dark"
              :content="$t('event.setting.additional.component.editCardnameDialog.tips1')"
              placement="top"
            >
              <span><i class="el-icon-question"></i>：</span>
            </el-tooltip>
          </div>
          <el-radio-group v-model="form.inputType" :disabled="form.id?true:false">
            <el-radio label="single">{{$t('common.base.onceTime')}}</el-radio>
            <el-radio label="multiple">{{$t('common.base.moreTime')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose('form')">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit('form')" v-if="id"
      >{{$t('common.base.makeSure')}}</el-button
      >
      <el-button type="primary" @click="onSubmit('form')" v-else
      >{{$t('common.base.nextStep')}}</el-button
      >
    </div>
  </base-modal>
</template>
<script>
// api
import * as SettingTaskApi from '@src/api/SettingTaskApi';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'

export default {
  name: 'edit-cardname-dialog',
  props: {
    id:{
      type: String,
    },
    from: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      form: {
        id: '',
        name: '',
        description: '',
        inputType: 'single'
      },
      nameLanguage:{},
      descriptionLanguage:{},
      rules: {
        name: [{ required: true, message: i18n.t('common.placeholder.inputName'), trigger: 'blur' }],
      },
    };
  },
  methods: {
    openDialog() {
      this.visible = true;
      if(this.id) {
        this.form.id = this.id;
        this.getCardInfoReq()
      }
    },
    onClose(form) {
      this.visible = false;
      this.$refs[form].resetFields();
      this.nameLanguage = {};
      this.descriptionLanguage = {};
    },
    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if(this.form.id){
            // 修改组件
            this.onUpdateCardReq(form);
          }else{
            // 新增组件
            this.onCreatCardReq();
           
          }
          this.visible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    
    // 创建附加组件
    onCreatCardReq() {
      const params = {
        description: this.form.description,
        inputType: this.form.inputType,
        name: this.form.name,
        titleLanguage: this.nameLanguage,
        descLanguage: this.descriptionLanguage
      }
      SettingTaskApi.onCreatCard(params).then(res=>{
        const { status, message, data } = res;
        if(status == 0){
          if(this.from === 'CreatCardDialog') this.$emit('onSuccess');

          this.$message.success(this.$t('common.base.tip.createSuccess'));
          setTimeout(()=>{
            let cardId = data;
            openAccurateTab({
              type:PageRoutesTypeEnum.PageTaskCardSetting,
              key:cardId,
              params:`cardId=${cardId}`
            })
          }, 1000)
        }else{
          this.$message.error(message);
        }
      }).catch(error=>{
        console.log(error)
      })
    },

    // 修改附加组件
    onUpdateCardReq(form) {
      const params = {
        description: this.htmlEscape(this.form.description),
        id: this.form.id,
        name: this.form.name,
        titleLanguage: this.nameLanguage,
        descLanguage: this.descriptionLanguage
      }
      SettingTaskApi.onUpdateCard(params).then(res=>{
        const { status, message, data } = res;
        if(status == 0){
          this.$message.success(this.$t('common.base.tip.editSuccess'));
          this.$emit('editCardSubmit');

          this.onClose(form);
        }else{
          this.$message.error(message);
        }
      }).catch(error=>{
        console.log(error)
      })
    },

    // 获取附加组件的信息
    getCardInfoReq() {
      SettingTaskApi.getCardInfo({id:this.form.id}).then(res=>{
        const { status, message, data } = res;
        if( status == 0 ){
          data.description = this.htmlUnEscape(data.description)
          this.form = data;
          this.nameLanguage = data?.titleLanguage || {};
          this.descriptionLanguage = data?.descLanguage || {};
        }
      }).catch(error=>({}))
    },
    
    // 防止XSS的恶意脚本攻击
    htmlEscape(value){
      return value.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    },
    htmlUnEscape(value){
      if(!value) return '';
      return value.replace( /&lt;/g, '<').replace(/&gt;/g, '>');
    },
    saveName(form) {
      this.nameLanguage = form;
      this.form.name = form[i18n.locale];
    },
    saveDescription(form) {
      this.descriptionLanguage = form;
      this.form.description = form[i18n.locale];
    }

  },
};
</script>
<style lang="scss">
.edit-dialog {
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-body {
    padding: 20px;
    .el-form {
      .el-form-item {
        .el-form-item__content {
          width: 280px;
          display: flex;
          .el-radio {
            margin-right: 24px;
          }
        }
        .el-tooltip {
            color: #999;
        }
      }
    }
  }
}
</style>